<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0                                                         |
// +------------------------------------------------------------------------+
// | Author: niuzhixin@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
namespace AuctionAppApi\Controller;

use AuctionCore\Sub\SubOrder;
use AuctionCore\CarDealer\Dealer;
use AuctionCore\System\AuctionException;
class SubscribeController extends BaseController{
    public $sub = null;
    public function __construct() {
        parent::__construct();
        if (empty($this->dealer_id)) {
            AuctionException::make_throw('500001');
        }
        $this->sub = new SubOrder($this->dealer_id);
    }
    /**
     * 订阅首页
     * @param int $dealer_id
     */
    public function index(){
        $data = array();
        $subscribe =  $this->sub->sel_sub($this->dealer_id);
        $data['max_count'] = 5;
        $data['items']=array();
        foreach($subscribe as $k=>$v){
            $data['items'][$k]['sid']=$v['sid'];
            $data['items'][$k]['header']['name']=$v['name'];
            $data['items'][$k]['header']['detail'] = $this->parse_key($v['sid']);
            $data['items'][$k]['body'] = $this->sub->get_index_order($v['sid']);
            $data['items'][$k]['footer']['type']=$this->sub->sel_order_count($v['sid'])>0?'all_order':'no_order';
            $data['items'][$k]['footer'][$this->sub->sel_order_count($v['sid'])>0?'number':'name'] =$this->sub->sel_order_count($v['sid'])>0?$this->sub->sel_order_count($v['sid']):'暂无符合条件的车，有新车会及时推送通知您！';
        }
        //print_r($data);die;
        //输出json数据
        $this->api_200($data);
    }
    /**
     * 订阅名称参数处理
     * @param int $sid
     */
    public function parse_key($sid){
        $str = '';
        $str_brand = '';
        $str_series = '';
        $str_prefix = '';
        $str_addr = '';
        $str_age = '';
        $str_emision = '';
        $dian = "●";
        $keys = $this->sub->sel_key_type($sid);
        foreach($keys as $k=>$v){
            switch($v['key_type']){
                case '1'://品牌
                        $cm = new \AuctionCore\CarResource\CarModel();
                        $brand = $cm->get_model_by_id($v['key_name'], 'brand');
                        $str_brand .= $brand['name'].' ' ;
                    break;
                case '2'://车系
                    $cm = new \AuctionCore\CarResource\CarModel();
                    $series = $cm->get_model_by_id($v['key_name'], 'series');
                    $str_series .= $series['name'].' ' ;
                    break;
                case '3'://注册地
                    if($v['key_name'] != -1){
                        $len = strlen($v['key_name']);
                        if($len > 1){
                            $pre = substr($v['key_name'],1,1);
                            if(is_numeric($pre)){
                                $prefix = substr($v['key_name'],0,$len - 1);
                                $suffix = substr($v['key_name'],-1);
                                $str_prefix .= C('PLATE_PREFIX.' . $prefix).$suffix.' ';
                            }else{
                                $prefix = substr($v['key_name'],0,1);
                                $suffix = substr($v['key_name'],1,1);
                                $str_prefix .= C('PLATE_PREFIX.' . $prefix).$suffix.' ';
                            }
                        }else{
                            $str_prefix .= C('PLATE_PREFIX.' . $v['key_name']);
                        }
                    }
                    break;
                case '4'://所在地
                    $addr = new \AuctionCore\Other\Address();
                    $str_addr .= $addr->get_name_by_code($v['key_name']).' ';
                    break;
                case '5'://年限
                    $str_age .= C('APP_AGE_RANGE.' . $v['key_name']).' ';
                    break;
                case '6'://排放
                    $str_emision .= C('INT_EMISSION_STD.' . $v['key_name']).' ';
                    break;
            }
        }
        //if(strpos($str_series,'全部') === false){
        $str .= $dian.$str_series;
        //}
        if($str_prefix != '' && $str_prefix != -1){
            $str .= $dian.$str_prefix;
        }
        if($str_addr != ' '){
            $str .= $dian.$str_addr;
        }
        if(strpos($str_age,'全部')  === false ){
            $str .= $dian.$str_age;
        }
        if(strpos($str_emision,'全部') === false){
            $str .= $dian.$str_emision;
        }
        //dump($keys,true,null,false);
        return $str;
    }
    /**
     * 删除订阅
     * @param int $sid
     */
    public function delete(){
        $sid = I("post.sid");
        /********参数合法性验证*********/
        $sub = $this->sub->sel_sub($this->dealer_id);
        if(!is_numeric($sid) || empty($sub)){
            AuctionException::make_throw('3000004');
        }
        $res = $this->sub->delete($sid);
        if($res === false){
            AuctionException::make_throw('3000001');
        }
        //输出json数据
        $this->api_200(null);
    }
    /**
     * 添加订阅
     */
    public function add(){
        $total = $this->sub->sel_sub_count($this->dealer_id);
        if($total>=5){
            AuctionException::make_throw('3000005'); //订阅数量达到上线
        }
        $sub_name = I('post.sub_name');//订阅名称
        //$brand_id = I('post.brand_id');//主品牌ID
        $series_id = I('post.series_id');//车系ID(多选)
        $reg_city = I('post.reg_city');//注册地(多选)
        $location_area = I('post.location_area'); //所在地(多选)
        $emission_std = I('post.emission');//排放标准（多选）
        $age_range = I('post.year');//年限（多选)
        if(empty($sub_name)){
            AuctionException::make_throw('3000003');
        }
        $list['dealer_id'] = $this->dealer_id;
        $list['name'] = $sub_name;
        $list['createtime'] = date('Y-m-d H:i:s');
        $sid = $this->sub->add($list);  //添加订阅名称
        if(!$sid>0){
            AuctionException::make_throw('3000002');
        }
        $data = array();
        $data['sid'] = $sid;
        $data['dealer_id'] = $this->dealer_id;
        $data['uid'] = $this->uid;
        $data['user_type'] = 2; //定义用户类型 2:表示车商
        $data['createtime'] = date('Y-m-d H:i:s');
        $info = array();
        //$brand = $this->sub->set_sub_key($data,$brand_id,1);//品牌
        $series = $this->sub->set_sub_key($data,$series_id,2);//车系
        $reg = $this->sub->set_sub_key($data,$reg_city,3);//注册地
        $location = $this->sub->set_sub_key($data,$location_area,4);//所在地
        $age = $this->sub->set_sub_key($data,$age_range,5);//年限
        $emission = $this->sub->set_sub_key($data,$emission_std,6);//排放
        $info = array_merge($series,$reg,$location,$age,$emission);
        $res = $this->sub->addall($info);
        if($res===false){
            AuctionException::make_throw('3000002');
        }
        $this->api_200(null);
    }
    /**
     * 订阅列表展示
     * @param int $sid
     */
    public function order_list() {
        $sid = I('post.sid');
        $page = I('post.page', '1');
        $page_size = I('post.page_size', '20');
        $cm = new \AuctionCore\CarResource\CarModel();
        $addr = new \AuctionCore\Other\Address();
        $dObj = new \AuctionCore\CarDealer\Dealer($this->dealer_id);
        $order_id = $this->sub->sel_order($sid);
        $map = array();
        $map['o.order_id'] = array('in',(is_array($order_id) && $order_id)?$order_id:array(0) );
        $map['o.status'] = array('in','3,301,4');
        $offset = ($page - 1) * $page_size;
        $limit_value = $offset . "," . $page_size;
        //dump($map);
        //计算符合条件的记录总数
        $total = $this->sub->sel_order_count($sid);
        $cols = "o.order_id,o.order_no,o.scene_id,o.status,os.starttime,
                    o.bid_start_price,o.bidding_best_price,o.bidding_start_time,o.act_elapsed_time,o.est_elapsed_time,o.coupon,o.rank,o.is_timing_order,o.show_reserve_price,
                    c.series_id,c.car_id,c.car_no,c.reg_city,c.first_reg_date,c.pointer_mileage,c.location_area,
                    c.plate_prefix,c.plate_suffix,c.composite_state,c.accident_level,c.car_cc,c.turbo,c.gearbox,
                    UNIX_TIMESTAMP(o.bidding_start_time)+IF(o.act_elapsed_time>o.est_elapsed_time,o.act_elapsed_time,o.est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time
                    ";
        $res = M('order')->alias('o')->field($cols)->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
            ->where($map)->order("o.bid_start_time desc")->limit($limit_value)->select();
        //echo M()->getLastSql();die;
        $list = array();
        foreach ($res as $key => $value) {
            $list[$key]['order_id'] = $value['order_id'];
            $list[$key]['order_no'] = $value['order_no'];
            //品牌车系车型
            $series = $cm->get_model_by_id($value['series_id'], 'series');
            //品牌车系车型
            $location_area = '['.$addr->get_name_by_code($value['location_area']).']';
            $list[$key]['car_name'] = $location_area.$series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
            //初登日期
            $list[$key]['first_reg_date'] = date('Y年m月', strtotime($value['first_reg_date']));
            //公里数格式转换
            $list[$key]['pointer_mileage'] = convert_mileage($value['pointer_mileage']);

            $list[$key]['plate_number'] = C('PLATE_PREFIX.' . $value['plate_prefix']) . substr($value['plate_suffix'], 0, 1);

            $list[$key]['desc'] = $list[$key]['first_reg_date'].'初登/'.$list[$key]['pointer_mileage'].'万公里/'.$list[$key]['plate_number'];

            ///汽车缩略图(不加oss图片处理参数)
            $car = new \AuctionCore\CarResource\Car($value['car_id']);
            $cond = "car_id='" . $value['car_id'] . "' AND pic_key='p_left_front45'";
            $pics = $car->get_pics('car_pictures', $cond);
            $list[$key]['img'] = $pics[0]['pic_url'];
            //是否关注
            $list[$key]['is_followed'] = $dObj->is_followed($value['order_id']) ? 1 : 0 ;
            //车况等级
            $list[$key]['composite_level'] = $value['composite_state'] . $value['accident_level'];
            //是否能用代金券
            $list[$key]['use_coupon'] = $value['coupon'] > 0 ? true : false;
            ///拍单状态
            $list[$key]['bidding_best_dealer_id'] = $value['bidding_best_dealer_id'];
            $list[$key]['state'] = $value['status'];
            //起拍价
            $list[$key]['bid_start_price'] = $value['bid_start_price'];

            switch ($value['status']) {
                case '3':
                    $list[$key]['status_cn'] = '投标中';
                    $my_last_bid_price = $dObj->get_my_last_bid_price($value['order_id']);
                    $list[$key]['my_last_bid_price'] = floatval($my_last_bid_price);
                    //交易服务费
                    $list[$key]['commision'] = $my_last_bid_price>0? get_commision($my_last_bid_price,$value['starttime']):get_commision($value['bid_start_price'],$value['starttime']);
                    //当前价
                    $price = $my_last_bid_price>0 ?$my_last_bid_price:$value['bid_start_price'];
                    break;
                case '301':
                    $list[$key]['status_cn'] = '待竞拍';
                    //交易服务费
                    $list[$key]['commision'] = get_commision($value['bid_start_price']);
                    //当前价
                    $price = $value['bid_start_price'];
                    break;
                case '4':
                    $list[$key]['status_cn'] = '竞拍中';

                    $my_last_bid_price = $dObj->get_my_last_bid_price($value['order_id']);
                    $list[$key]['my_last_bid_price'] = floatval($my_last_bid_price);

                    $my_last_bidding_price = $dObj->get_my_last_bidding_price($value['order_id']);
                    $list[$key]['my_last_bidding_price'] = floatval($my_last_bidding_price);
                    //交易服务费
                    $list[$key]['commision'] = get_commision($value['bidding_best_price']>0? $value['bidding_best_price']:$value['bid_start_price']);
                    //当前价
                    $price = $value['bidding_best_price']>$value['bid_start_price']?$value['bidding_best_price']:$value['bid_start_price'];
                    break;
            }
            //当前价格
            $list[$key]['price'] = intval($price);
            //交付服务费
            $list[$key]['transfer_fee'] = intval($value['transfer_fee']);
            /*************************计算剩余时间**********************************/
            //结束时间（竞拍结束时间、投标结束时间 时间戳）
            $list[$key]['starttime'] = strtotime($value['starttime'])*1000;
            $list[$key]['bidding_start_time'] = strtotime($value['bidding_start_time'])*1000;
            $list[$key]['act_elapsed_time'] = $value['act_elapsed_time']*1000;
            $list[$key]['est_elapsed_time'] = $value['est_elapsed_time']*1000;

            //是否显示保留价
            $list[$key]['show_reserve_price'] = $value['show_reserve_price']>0?true:false;
        }
            $data = array();
            $data['title'] = "竞拍中的拍单";
            $list_filter = array_filter($list);
            if (empty($list_filter)) {
                $data['title'] = "";
            }
            $data['currentpage'] = $page;
            $data['pagesize'] = $page_size;
            $data['maxcount'] = $total;
            $data['maxpage'] = ceil($total / $page_size);
            $data['list'] = $list;
            //输出json数据
            $this->api_200($data);
    }
}